package com.orz.mall.controller.user;

import com.orz.mall.mall.IUserService;
import com.orz.mall.mall.beans.user.User;
import com.orz.mall.util.ResponseUtil;
import com.orz.mall.util.excel.ExcelUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired(required = false)
    private IUserService userService;

    @GetMapping(value = "/list")
    public List<User> findAll(){
        return userService.findAllUser();
    }

    @GetMapping("/get/{id}")
    public User findUserById(@PathVariable Integer id){
        return userService.findUserById(id);
    }


    /**
     * 
     * @param response
     */
    @GetMapping(value = "/exportall")
    public void exportAll(HttpServletResponse response) throws UnsupportedEncodingException {
        String fileName = "用户列表";
        //sheet页名称
        String sheetName = "用户列表";
        OutputStream outputStream = ResponseUtil.getOutputStream(fileName, response);
        String[] titiles = {"用户名","密码","年龄"};
        List <User> users = userService.findAllUser();
        //封装要导出的数据s
        List<List<String>> lists = new LinkedList <List <String>>();
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            List<String> list = new LinkedList <String>();
            list.add(user.getName());
            list.add(user.getPassword());
            list.add(String.valueOf(user.getAge()));
            lists.add(list);
        }
        try {
            XSSFWorkbook workbook = new XSSFWorkbook();
            ExcelUtils.exportExcel(sheetName,titiles,lists,workbook,outputStream);
        } catch (IOException e) {
            LOGGER.error("导出用户列表异常");
        }
    }
}
